﻿using DevelopTool.Common;
using DevelopTool.Model.CommonModels;
using DevelopTool.Model.Enums;
using DevelopTool.Model.PowerPlanModels;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Linq;

namespace DevelopTool.Bll.PowerPlanBlls
{
    public class PowerPlanBll
    {
        /// <summary>
        /// 电源计划保持时间
        /// </summary>
        public static long TempTimeSeconds = 0;

        /// <summary>
        /// 启动电源计划监控
        /// </summary>
        public void StartJob()
        {
            QuartzHelper.DeleteJob("PowerPlanJob","PowerPlanGroup");
            if(!QuartzHelper.AddSimpleTriggerJob(typeof(PowerPlanJob),"PowerPlanJob","PowerPlanGroup",-1,2,DateTime.Now,DateTime.Now.AddYears(100)))
            {
                PowerPlanLogBll.AddLog(new LogModel(Model.Enums.LogType.Warning,$"自动电源计划启动失败"));
            }
        }


        /// <summary>
        /// 获取当前电源计划对象
        /// </summary>
        /// <returns></returns>
        public static Powercfg GetCurrentPowercfg()
        {
            return GetPowercfgList().FirstOrDefault(it => it.IsActive);
        }

        /// <summary>
        /// 设置系统电源计划，并返回设置后的电源计划对象
        /// </summary>
        /// <param name="powercfg"></param>
        public static Powercfg ChangePowerPlan(string powercfgUUID)
        {
            SystemEx.RunDosCmd("powercfg -setactive " + powercfgUUID);
            return GetCurrentPowercfg();
        }

        /// <summary>
        /// 获取电源计划配置列表
        /// 现有电源使用方案 (* 表示当前使用的电源方案)
        /// </summary>
        /// <returns>List<Dictionary<string, string>></returns>
        public static List<Powercfg> GetPowercfgList()
        {
            string powercfgStr = SystemEx.RunDosCmd("powercfg /l");

            powercfgStr = powercfgStr.Substring(powercfgStr.IndexOf("电源方案 GUID: "));

            powercfgStr = powercfgStr.Replace("电源方案 GUID","");
            string[] powercfgArray = powercfgStr.Split(":".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
            List<Powercfg> list = new List<Powercfg>();
            foreach(string powercfgInfo in powercfgArray)
            {
                if(!string.IsNullOrEmpty(powercfgInfo))
                {
                    Powercfg powercfg = new Powercfg
                    {
                        IsActive = powercfgInfo.Contains("*")
                    };

                    string powercfgInfo1 = powercfgInfo.Replace(" ","").Replace("\r\n","");

                    powercfg.UUID = powercfgInfo1.Substring(0,powercfgInfo1.IndexOf("("));

                    string powercfgName = powercfgInfo1.Substring(powercfgInfo1.IndexOf("("));
                    powercfgName = powercfgName.Substring(0,powercfgName.IndexOf(")")).Replace("(","");
                    powercfg.Name = powercfgName;

                    list.Add(powercfg);
                }
            }
            return list;
        }


    }
}
